/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hannesdorfmann.swiperefresh.util;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.ScrollView;

/**
 * @date 2020/12/27
 */

public class ScrollUtil {

    /**
     * Determine whether the child has scrolled
     *
     * @param child
     * @return true
     */
    public static boolean childScrolled(Component child) {
        if (child instanceof ScrollView) {
            ScrollView scrollView = (ScrollView) child;
            if (scrollView.getComponentAt(0) != null
                    && scrollView.getComponentAt(0).getTop() < 0) {
                return true;
            }
        } else if (child.getScrollValue(Component.AXIS_Y) > 0) {
            return true;
        }
        if (child instanceof ListContainer) {
            ListContainer listContainer = (ListContainer) child;
            Component component = listContainer.getComponentAt(0);
            int firstPosition = listContainer.getIndexForComponent(component);
            return firstPosition != 0 || component.getTop() != 0;
        }
        return false;
    }

    /**
     * Find a child that can be scrolled
     *
     * @return Scrollable child
     */
    public static Component findScrollableChild(ComponentContainer componentContainer) {
        Component child = componentContainer.getComponentAt(1);
        if (child instanceof ScrollView || child instanceof ListContainer) {
            return child;
        }
        if (child instanceof ComponentContainer) {//One more layer down
            Component tempChild = ((ComponentContainer) child).getComponentAt(0);
            if (tempChild instanceof ScrollView || tempChild instanceof ListContainer) {
                child = tempChild;
            }
        }
        return child;
    }
}
